# coding=utf-8
import xlrd,arcpy, arcgisscripting, sys, os

def excel2Class(excelPath):
    excelFile = xlrd.open_workbook(excelPath)
    sheet = excelFile.sheet_by_index(0)
    geometries = []
    for i in range(1, sheet.nrows):
        row = sheet.row_values(i)
        data = row[1]
        a_count = data.count("(")
        b_count = data.count(")")
        if a_count == b_count:
            continue
        arcpy.AddMessage('row:{0}'.format(i+1))
        data_list = data.split(',')
        # arcpy.AddMessage('data list end:{0},{1}'.format(data_list[-2],data_list[-1]))
        j = 0
        polygons = []
        while j < len(data_list):
            data_xy = data_list[j].split(' ')[-2:]
            if data_xy[0].find('(') >= 0:
                polygon = []
                x = data_xy[0].split('(')[-1]
                y = data_xy[1]
                polygon.append([x, y])
            elif data_list[j].find(')') >= 0 or j + 1 >= len(data_list):
                # arcpy.AddMessage('fea end data:{0}'.format(data_list[j]))
                if len(data_list[j].split(' ')) >= 2:
                    x = data_xy[0]
                    y = data_xy[1].split(')')[0]
                    polygon.append([x, y])
                polygons.append(polygon)
            else:
                x = data_xy[0]
                y = data_xy[1]
                polygon.append([x, y])
            j = j + 1
        geometries.append(polygons)
    print geometries
    return geometries


# path = 'E:\\PythonProject\\africa\\doc\\africa\\data\\origin\\Murdock_EA_2011_vkZ.xls'
# excel2Class(path)


excelPath = 'E:\\PythonProject\\africa\\doc\\africa\\data\\origin\\Murdock_EA_2011_vkZ.xls'

geometries = excel2Class(excelPath)
gp = arcgisscripting.create()
gp.OverwriteOutput = 1
outputShpPath = sys.argv[1]
outWorkspace = os.path.split(outputShpPath)[0]
shpName = os.path.split(outputShpPath)[-1]
spat_ref = "4326"
gp.CreateFeatureClass_management(outWorkspace, shpName, "POLYGON", "", "", "", spat_ref)
cur = gp.InsertCursor(outputShpPath)
newRow = cur.newRow()
for i in range(0, len(geometries)):
    arcpy.AddMessage('geometry:{0}'.format(i))
    feaPolygons = geometries[i]
    for j in range(0, len(feaPolygons)):
        feaPolygon = feaPolygons[j]
        pnt = gp.CreateObject("point")
        array = gp.CreateObject("array")
        for k in range(0,len(feaPolygon)):
            pos = feaPolygon[k]
            # arcpy.AddMessage('pos:{0}'.format(pos))
            if pos[0] and pos[1]:
                pnt.X, pnt.Y = pos[0], pos[1]
                array.add(pnt)
        newRow.Shape = array
        cur.InsertRow(newRow)
del cur, newRow
